package pool

import (
	"bytes"
	"context"
	"fmt"

	"github.com/PuerkitoBio/goquery"
	"xtsec.com/dns-syncer/common/tools"
)

const ipshuLookup = "https://zh-hans.ipshu.com/myip_info"

type ipshu struct{ base }

func NewIpshu() *ipshu {
	return &ipshu{base: base{lookup: ipshuLookup, target: "ipshu"}}
}

func (ipshu ipshu) GetIPResponse(ctx context.Context) (IPResponse, error) {
	ir := IPResponse{Target: ipshu.target}

	var buf bytes.Buffer
	err := ipshu.client().ToBytesBuffer(&buf).Fetch(ctx)
	if err != nil {
		return ir, err
	}

	doc, err := goquery.NewDocumentFromReader(bytes.NewReader(buf.Bytes()))
	if err != nil {
		return ir, err
	}

	node := doc.Find("body > div > ul > li:nth-child(1) > p > a").First()
	if node == nil {
		return ir, fmt.Errorf("empty node found")
	}

	ir.Ip = node.Text()

	if err := tools.ValidateStruct(ir); err != nil {
		return ir, err
	}

	return ir, nil
}
